module.exports = (function() {
    var express = require('express');
    var router = express.Router();
    var nhe = require('./node-highcharts-exporter');
    var fs = require('fs');

    router.post('/', function(request, response) {

        var highchartsExportRequest = request.body;
        nhe.exportChart(highchartsExportRequest, function(error, exportedChartInfo) {
            if (error) { // Send an error response
                response.send(error);
            } else { // Send the file back to client
                response.set("Content-Disposition", "attachment;filename=" + encodeURI(exportedChartInfo.downloadName));
                var filestream = fs.createReadStream(exportedChartInfo.filePath);
                filestream.pipe(response);
                filestream.on('end', (function(parentDir) {
                    return function() {
                        fs.rmdir(exportedChartInfo.parentDir, function() {});
                    };
                })(exportedChartInfo.parentDir));
            }
        });
    });
    return router;
})();
